# coding: utf-8
import datetime

from sqlalchemy import Column, DateTime, String, func
from sqlalchemy.dialects.mysql import LONGTEXT, TINYINT, VARCHAR
from sqlalchemy.ext.declarative import declarative_base
from ..utils.response_code import RET
from ..utils import commons


Base = declarative_base()
metadata = Base.metadata

# 初始化数据库连接:


class InformationCode(Base):
    __tablename__ = 'information_codes'

    codeID = Column(VARCHAR(30), primary_key=True, comment='节点主键')
    codeName = Column(VARCHAR(255), nullable=False, comment='节点名称')
    parentCodeID = Column(VARCHAR(30), nullable=False, server_default='0', comment='父节点ID（0表示是第一个节点）')
    createTime = Column(DateTime, nullable=False, server_default="CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP", comment='创建时间')

    @classmethod
    def add_code_info(cls, **kwargs):
        engine = commons.get_mysql_engine()
        session = commons.get_mysql_session(engine)

        code_name = kwargs.get('codeName')
        parent_code_ID = kwargs.get('parentCodeID') if kwargs.get('parentCodeID') else "0"

        try:
            code_ID = datetime.datetime.now().strftime('%Y%m%d%H%M%S')+str(datetime.datetime.now()).split(".")[1]

            filter_list = []
            filter_list.append(cls.codeName == code_name)

            codeInfo = session.query(cls).filter(*filter_list)

            if codeInfo.first():
                return {'code': RET.DATAERR, 'message': '重复的数据'}

            CodeInfomation = InformationCode(codeID=code_ID,
                                             codeName=code_name,
                                             parentCodeID=parent_code_ID,
                                             )
            session.add(CodeInfomation)
            session.commit()
        except Exception as e:
            session.rollback()
            return {'code': RET.DBERR, 'message': '插入数据库失败', 'error': str(e)}
        finally:
            engine.dispose()
            session.remove()
        # data = commons.query_to_dict(CodeInfomation)
        back_data = {
            "codeID": code_ID,
            "codeName": kwargs.get('codeName'),
            "parentCodeID": kwargs.get('parentCodeID')
        }
        return {'code': RET.OK, 'message': '插入数据库成功', 'data': back_data}


class InformationInfo(Base):
    __tablename__ = 'information_info'

    informationID = Column(String(30), primary_key=True, comment='资料主键')
    title = Column(VARCHAR(255), nullable=False, comment='标题')
    text = Column(LONGTEXT, comment='资料内容')
    parentCodeID = Column(VARCHAR(30), nullable=False, server_default='0', comment='父节点')
    createTime = Column(DateTime, nullable=False, server_default="CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP", comment='创建时间')

    @classmethod
    def add_detail_info(cls, **kwargs):
        engine = commons.get_mysql_engine()
        session = commons.get_mysql_session(engine)

        title = kwargs.get('title')
        text = kwargs.get('text')
        parent_code_ID = kwargs.get('parentCodeID') if kwargs.get('parentCodeID') else "0"

        try:
            infomation_ID = (datetime.datetime.now()).strftime('%Y%m%d%H%M%S')

            filter_list = []
            filter_list.append(cls.title == title)

            infomation = session.query(cls).filter(*filter_list)

            if infomation.first():
                return {'code': RET.DATAERR, 'message': '重复的数据'}

            Infomation = InformationInfo(informationID=infomation_ID,
                                         title=title,
                                         text=text,
                                         parentCodeID=parent_code_ID,
                                         )
            session.add(Infomation)
            session.commit()
        except Exception as e:
            session.rollback()
            return {'code': RET.DBERR, 'message': '插入数据库失败', 'error': str(e)}
        finally:
            engine.dispose()
            session.remove()

        # data = commons.query_to_dict(Infomation)
        back_data = {
            "infomationID": infomation_ID,
            "title": kwargs.get('title'),
            "text": kwargs.get('text'),
            "parentCodeID": kwargs.get('parentCodeID')
        }
        return {'code': RET.OK, 'message': '插入数据库成功', 'data': back_data}

    @classmethod
    def find_detail_info(cls, **kwargs):
        pass